package com.sa07.filesave.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sa07.bean.TestItemBean;
import com.sa07.db.DefaultSession;
import com.sa07.filesave.IFileSave;

/**
 * 文件保存：1.保存数据库;2.保存本地txt文件;
 * @author hu.shiguo
 * 2014-2-18
 * 下午10:40:27
 */
public class FileSaveImpl implements IFileSave {

	public static BufferedReader reader;
	//文件保存路径
	private static String savePath = "D:/测试结果.txt";
	private static File fileName = new File(savePath);
	private static String readStr = "";
	
	protected static final Logger logger = Logger
			.getLogger(DefaultSession.class);
	

	@Override
	public void saveAstxt(List<Map<String, Object>> params) {
		fileName = new File (savePath); 
		String  testTime = ""; 
		String  operator = ""; 
		String  roleName = ""; 
		String  testResult = ""; 
		String  resultCode = ""; 
		String  resultExplain = ""; 
		if(params != null && !params.isEmpty()){
			try {
				StringBuffer newStr = new StringBuffer("");
				createTextFile();
				readTxtFile();
				for (Map<String, Object> map : params) {
					testTime = getMapKey(map, "testTime");
					operator = getMapKey(map, "operator");
					roleName = getMapKey(map, "roleName");
					testResult = getMapKey(map, "testResult");
					resultCode = getMapKey(map, "resultCode");
					resultExplain = getMapKey(map, "resultExplain");
					newStr.append(testTime+",").append(operator+",").append(roleName+",").
					append(testResult+",").append(resultCode+",").append(resultExplain+"\r\n");
					if(null != newStr && newStr.length()>0){
						writeTextFile(newStr.toString());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("create text file failed, caused by -> " + e);
			}
		}
		
	}

	@Override
	public void saveAsDataBase(TestItemBean itemBean) {
		
		
		
		
	}
	
	
	/**
	 * 创建文本文件
	 * @throws IOException 
	 * @param fileName
	 * @throws IOException
	 */
	public static void createTextFile() throws IOException {
		if(!fileName.exists()){
			fileName.createNewFile();
			logger.info("create(" + fileName + ") success ");
		}
	}

	   /**
     * 读取文本文件.
     * 
     */
    public static String readTxtFile(){
        String read;
        FileReader fileread;
        try {
            fileread = new FileReader(fileName);
            reader = new BufferedReader(fileread);
            try {
                while ((read = reader.readLine()) != null) {
                    readStr = readStr + read+ "\r\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
       // System.out.println("文件内容是:"+ "\r\n" + readStr);
        return readStr;
    }
    
	/**
	 * 写文件
	 * @param newStr
	 */
	public static void writeTextFile(String newStr){
		String filein = newStr +"\r\n"+readStr+"\r\n";
		RandomAccessFile mm = null;
		try {
			mm = new RandomAccessFile(fileName, "rw");
			mm.writeBytes(filein);
			
		} catch (IOException  e1) {
			e1.printStackTrace();
			logger.error("Execute save(" + fileName + ") failed, caused by -> " + e1);
		}finally{
			if(null != mm){
				try {
					mm.close();
				} catch (IOException e2) {
					e2.printStackTrace();
					logger.error("close RandomAccessFile failed, caused by -> " + e2);
				}
			}
		}
	}
	
	/**
	 * 根据key获取map value
	 * @param map
	 * @param key
	 * @return
	 */
	public String getMapKey(Map<String, Object> map,String key){
		String str = "";
		if(null != map.get(key) && !map.get(key).equals("")){
			str = (String)map.get(key);
		}
		return str; 
	} 
	
	public static void main(String[] args) throws IOException {
		//FileSaveImpl.createTextFile();
		//FileSaveImpl.readTxtFile();
		//FileSaveImpl.writeTextFile("20140218235730,hushiguo,admin,no problem,1000,aaaaa");
		FileSaveImpl impl = new FileSaveImpl();
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("testTime", "20140219003511");
		map1.put("operator", "longshangbo");
		map1.put("roleName", "admin");
		map1.put("testResult", "no problem");
		map1.put("resultCode", "1000");
		map1.put("resultExplain", "aaaa");
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("testTime", "20140219003812");
		map2.put("operator", "hushiguo");
		map2.put("roleName", "admin");
		map2.put("testResult", "have problem");
		map2.put("resultCode", "1001");
		map2.put("resultExplain", "bbbb");
		List<Map<String, Object>> params = new ArrayList<Map<String,Object>>();
		params.add(map1);
		params.add(map2);
		impl.saveAstxt(params);
	}
}
